﻿using BCCommon;
using BCEntity.TMS.MarketingCoupon.MarketingCouponReceive;
using Dapper;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;

namespace BCData.TMS.MarketingCoupon.MarketingCouponReceive
{
    public class MarketingCouponReceiveData : IMarketingCouponReceiveData
    {
        private const string QUERY_EXISTS = @"SELECT 1 FORM marketingcouponreceive";
        private const string SQL_QUERY = @" SELECT
		                                    A.MarketingCouponReceiveId,
		                                    A.UserId,
		                                    A.UserName,
		                                    A.MarketingCouponTypeId,
		                                    A.CouponType,
		                                    A.MarketingCouponId,
		                                    A.CouponNumber,
		                                    A.CouponName,
		                                    A.CouponSummark,
		                                    A.AgentRecordId,
		                                    A.IsCommon,
		                                    A.ProvinceCode,
		                                    A.CityCode,
		                                    A.CountyCode,
		                                    A.StartDate,
		                                    A.EndDate,
		                                    A.CouponAmount,
		                                    A.CreateTime,
		                                    A.IsCommonBusiness,
		                                    A.VehicleTransportBusinessConfigId,
		                                    A.TransportBusiness
                                        FROM
                                            marketingcouponreceive A ";


        private readonly IDatabaseContext database;
        public MarketingCouponReceiveData(IDatabaseContext database)
        {
            this.database = database;
        }

        public async Task<MarketingCouponReceiveEntity> GetEntityByCouponId(long marketingCouponId)
        {
            var sql = $" {SQL_QUERY} WHERE A.MarketingCouponId=?MarketingCouponId ";
            return await this.database.Slave.QueryFirstOrDefaultAsync<MarketingCouponReceiveEntity>(sql, new { marketingCouponId });
        }
        public async Task<bool> Exsits(long userId, long marketingCouponId)
        {
            string sql = string.Format("{0} WHERE MarketingCouponId=?MarketingCouponId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?MarketingCouponId", marketingCouponId, DbType.Int64);
            return await this.database.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<MarketingCouponReceiveEntity> GetEntityById(long marketingCouponReceiveId)
        {
            var sql = typeof(MarketingCouponReceiveEntity).GetSelectSqlByPrimaryKeys();
            return await this.database.Slave.QueryFirstOrDefaultAsync<MarketingCouponReceiveEntity>(sql, new { marketingCouponReceiveId });
        }

        public async Task<MarketingCouponReceiveEntity> InsertAsync(MarketingCouponReceiveEntity entity)
        {
            return await this.database.Master.InsertAsync(entity, database.Transaction);
        }

        public async Task<(IEnumerable<MarketingCouponReceiveEntity>, int)> Query(long? marketingCouponTypeId, long? userId,bool? isInvalid,
            bool? isUse,int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (marketingCouponTypeId.HasValue)
            {
                wheres.Add(" A.MarketingCouponTypeId= ?MarketingCouponTypeId ");
                parameters.Add("?MarketingCouponTypeId", marketingCouponTypeId, DbType.Int64);
            }
            if (userId.HasValue)
            {
                wheres.Add(" A.UserId= ?UserId ");
                parameters.Add("?UserId", userId.Value, DbType.Int64);
            }
            if (isInvalid.HasValue)
            {
                if (isInvalid.Value)
                {
                    wheres.Add(" A.EndDate>= CURDATE() ");
                }
                else
                {
                    wheres.Add(" A.EndDate< CURDATE() ");
                }
            }
            if (isUse.HasValue)
            {
                if (isUse.Value)
                {
                    wheres.Add("  A.StartDate<=CURDATE() AND A.EndDate>= CURDATE() ");
                }
                else
                {
                    wheres.Add(" (A.EndDate< CURDATE() || A.StartDate>CURDATE())");
                }
            }
            string whereSql = string.Empty;
            if (wheres.Count > 0)
            {
                whereSql = $"WHERE {string.Join(" AND ", wheres)} ";
            }
            var sqlCount = " SELECT COUNT(A.MarketingCouponReceiveId) FROM MarketingCouponReceive A ";
            string sql = $@"{SQL_QUERY} {whereSql} Order By A.MarketingCouponReceiveId DESC
                            LIMIT {(pageIndex - 1) * pageSize}, {pageSize};{sqlCount}{whereSql} ";
            return await this.database.Slave.QueryPageableListAsync<MarketingCouponReceiveEntity>(sql, parameters);
        }

        public async Task<MarketingCouponReceiveEntity> UpdateAsync(MarketingCouponReceiveEntity entity)
        {
            return await this.database.Master.UpdateAsync(entity, database.Transaction);
        }


    }
}
